package com.mms.context;

import com.mms.controller.admin.WelController;
import com.mms.pojo.SysManager;
import com.mms.pojo.SysOperate;
import com.mms.service.SysManagerService;
import com.mms.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by dan3652@sina.com on 2016-11-25 10:43.
 */
public class AdminContextInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AdminContextInterceptor.class);
    private String loginUrl;
    private List uncheckUrls;
    /**
     * 在controller后拦截   afterCompletion
     */
    private void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            String requestType = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestType)) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/json");
                response.setDateHeader("Expires", 0);
                response.getWriter().write("{\"sessionTimeout\": true}");
            } else {
                response.sendRedirect(loginUrl);
            }
            request.setAttribute(Constants.MESSAGE, "未登录");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在controller前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 处理不拦截
         */
        String requestUri = RequestUtils.getURI(request);
        if(uncheckUrls.contains(requestUri)){
            return true;
        }
        /**
         * 获取URL
         */
        String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
        request.setAttribute(Constants.SYSTEM_URL,path);
        if ( 80 == request.getServerPort()){
            request.setAttribute(Constants.SYSTEM_URL,request.getScheme()+"://"+request.getServerName()+request.getContextPath()+"/");
        }
        SysManager member = null;
        //判断登录是否过期，是否登录
        request.setAttribute(Constants.USER_IN_REQUEST,1);
        Long userid = Long.valueOf(request.getAttribute(Constants.USER_IN_REQUEST)+"");
        member = sysManagerService.get(userid);
//        System.out.println("处理拦截===========================");
        request.setAttribute(Constants.USER_IN_REQUEST, member);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {
        String uri = RequestUtils.getURI(request);
        if(!(handler instanceof WelController)) {
            String message = null;
            if (ex != null) {
                message = ex.getMessage();
            } else {
                message = (String) request.getAttribute("actionMessages");
            }
            SysOperate operate = (SysOperate) request.getAttribute(Constants.OP_IN_REQUEST);
            if (operate != null && !"列表".equals(operate.getName() ) ){
                SysManager account = (SysManager) request.getAttribute(Constants.USER_IN_REQUEST);
               /* SysLogs logs = new SysLogs();
                if (account != null) {
                    logs.setSysManager(null);
                }
                String param = RequestUtils.getQueryString(request);
                if (operate != null) {
                    logs.setOpeCode(operate.getSysMenu().getName() + "-"
                            + operate.getName());
                }
                //logs.setClazz(handler.getClass().getName());
                //logs.setParams(param);
                //logs.setUri(uri);
                logs.setId(UUID.randomUUID().toString().replace("=",""));
                logs.setOpeContent(param+"-"+handler.getClass().getName());
                logs.setOpeIp(RequestUtils.getIpAddr(request));
                logs.setOpeDate(sdf.format(new Date()));
                logs.setSysManager(account);
                gdsOplogService.save(logs);*/
            }
        }
        if (ex != null) {
            logger.error("", ex);
            try {
                String requestType = request.getHeader("X-Requested-With");
                if ("XMLHttpRequest".equals(requestType)) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/json");
                    response.setDateHeader("Expires", 0);
                    response.getWriter().write("{\"error\": \"" + ex.getMessage() + "\"}");
                } else {
                    response.getWriter().write(ex.getMessage());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Autowired
    private SysManagerService  sysManagerService;

    public void setUncheckUrls(List uncheckUrls) {
        this.uncheckUrls = uncheckUrls;
    }

    public List getUncheckUrls() {
        return uncheckUrls;
    }

    public static Logger getLogger() {
        return logger;
    }

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }
}
